/*****************************************************************************
 * HUSONG PROPRIETARY INFORMATION
 * <p/>
 * The information contained herein is proprietary to HUSONG
 * and shall not be reproduced or disclosed in whole or in part
 * or used for any design or manufacture
 * without direct written authorization from HUSONG.
 * <p/>
 * Copyright (c) 2015 by HUSONG.  All rights reserved.
 *****************************************************************************/
package com.husong.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.husong.controller.base.BaseController;
import com.husong.entity.BatchWithdrawOrder;
import com.husong.entity.Institution;
import com.husong.entity.User;
import com.husong.entity.WithdrawOrder;
import com.husong.pojo.AliWithdrawReturnRecord;
import com.husong.util.PointUtil;
import com.husong.util.PointcutRuleUtil;
import com.husong.util.PointcutUtil;
import com.husong.util.alipay.util.AlipayNotify;


/**
 * 首页
 *
 * @author maxmin
 */
@Controller
@RequestMapping()
public class IndexController extends BaseController {


//    @RequestMapping("/index")
//    @ResponseBody
//    public ReturnJsonBean index(Integer type,String cityname,String lastDate,Long lastorderid) {
//        ReturnJsonBean rb = new ReturnJsonBean();
//        try {
//            List<Order> list = orderService.findAll(type,cityname,lastDate,lastorderid);
//            rb.setData(list);
//            returnSuccess(rb);
//        } catch (Exception e) {
//            e.printStackTrace();
//            saveException(AuthodType.jincongmin.getName(), "IndexController", "index()", e);
//        }
//        return rb;
//    }
//
//    @RequestMapping("/broker/count")
//    @ResponseBody
//    public ReturnJsonBean brokerCount(String cityname) {
//        ReturnJsonBean rb = new ReturnJsonBean();
//        try {
//            Long count = userService.brokerCount(cityname);
//            Map<String, Object> map = new HashMap<String, Object>();
//            rb.setData(map);
//            returnSuccess(rb);
//        } catch (Exception e) {
//            e.printStackTrace();
//            saveException(AuthodType.jincongmin.getName(), "IndexController", "index()", e);
//        }
//        return rb;
//    }
    
    @RequestMapping(value="/success")
	public ModelAndView success(HttpServletRequest request,String userid,Model model) {
		ModelAndView modelAndView = new ModelAndView(
				"index");
		User user=userService.get(userid);
		String title=PointUtil.convertToTitle(user.getPoint());
		Long point=user.getPoint();
		Map<String,Object> map1=PointcutUtil.convertToPointcut(point);
		List<Map<String, Object>> list=PointcutRuleUtil.convertToRule(point);
		model.addAttribute("userid", userid);
		model.addAttribute("title", title);
		model.addAttribute("point", point);
		model.addAttribute("map1", map1);
		model.addAttribute("list", list);
		return modelAndView;
	}
    
    @RequestMapping(value="/institution")
    public ModelAndView institution(HttpServletRequest request,String userid,Model model) {
    	ModelAndView modelAndView = new ModelAndView(
    			"broker_institution");
    	List<Institution> list=userService.getInstitutions();
    	model.addAttribute("institutions", list);
    	return modelAndView;
    }
    
    @RequestMapping(value="/alipay/batch/notify_url", method = RequestMethod.POST)
	public void alipayBatchNotify(HttpServletRequest request,HttpServletResponse response) {
//		logger.info("alipay_notify:begin"+request.getParameterMap());
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
//		logger.info("alipay_notify:params"+params);
		
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e1) {
//			logger.info("alipay_notify:fail"+e1);
			e1.printStackTrace();
		}
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//批量付款数据中转账成功的详细信息

		String success_details=null;
		//批次号
		String batch_no=null;
		//回调ID
		String notify_id=null;
		//批量付款数据中转账失败的详细信息
		String fail_details=null;
		try {
			String success_detail=request.getParameter("success_details");
			if(success_detail!=null){
				success_details = new String(success_detail.getBytes("ISO-8859-1"),"UTF-8");
			}
			batch_no = new String(request.getParameter("batch_no").getBytes("ISO-8859-1"),"UTF-8");
			notify_id = new String(request.getParameter("notify_id").getBytes("ISO-8859-1"),"UTF-8");
			String faildetail=request.getParameter("fail_details");
			if(faildetail!=null){
				fail_details = new String(faildetail.getBytes("ISO-8859-1"),"UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
//			logger.info("alipay_notify:fail"+e);
			out.println("fail");
			return;
		}

		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

		if(AlipayNotify.verify(params)){//验证成功
			//////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代码
			List<WithdrawOrder> orders=userService.queryAliWithdrawOrdersByBatchOrderNo(batch_no);
			
			Map<String,WithdrawOrder> orderMap=new HashMap<String, WithdrawOrder>();
			for(WithdrawOrder order:orders){
				orderMap.put(order.getWithdraw_order_no(), order);
			}
			try {
			if(success_details!=null){
				List<AliWithdrawReturnRecord> successRecords=analysisAliWithdrawReturnRecode(success_details);
				Map<String,WithdrawOrder> successMap=new HashMap<String, WithdrawOrder>();
				for(AliWithdrawReturnRecord successRecord:successRecords){
					WithdrawOrder order=orderMap.get(successRecord.getWithdrawOrderNo());
					if(order!=null){
						order.setNotify_desc(successRecord.getRemark());
						successMap.put(successRecord.getWithdrawOrderNo(), order);
					}
				}
				userService.dealWithSuccessAliBatchWithdrawResult(successMap, batch_no, notify_id);
			}
			if(fail_details!=null){
				List<AliWithdrawReturnRecord> failRecords=analysisAliWithdrawReturnRecode(fail_details);
				Map<String,WithdrawOrder> failMap=new HashMap<String, WithdrawOrder>();
				for(AliWithdrawReturnRecord failRecord:failRecords){
					WithdrawOrder order=orderMap.get(failRecord.getWithdrawOrderNo());
					if(order!=null){
						order.setNotify_desc(failRecord.getRemark());
						failMap.put(failRecord.getWithdrawOrderNo(), order);
					}
				}
				userService.dealWithFailAliBatchWithdrawResult(failMap, batch_no, notify_id);
			}
//			
//				logger.info("alipay_notify:success");
				out.println("success");
				return;
			} 
		catch (Exception e) {
//				logger.info("alipay_notify:fail"+e);
				out.println("fail");
				return;
			}
			

			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			
			//判断是否在商户网站中已经做过了这次通知返回的处理
				//如果没有做过处理，那么执行商户的业务程序
				//如果有做过处理，那么不执行商户的业务程序
				
//			return "success";//请不要修改或删除

			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

			//////////////////////////////////////////////////////////////////////////////////////////
		}else{//验证失败
//			logger.info("alipay_notify:fail verify");
			out.println("fail");
			return;
		}
	}
    
    
    private List<AliWithdrawReturnRecord> analysisAliWithdrawReturnRecode(String return_details){
		String[] details=return_details.split("\\|");
		List<AliWithdrawReturnRecord> records=new ArrayList<AliWithdrawReturnRecord>();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		for(String detail:details){
			String[] detailArr=detail.split("\\^");
			AliWithdrawReturnRecord record=new AliWithdrawReturnRecord();
			record.setWithdrawOrderNo(detailArr[0]);
			record.setWithdrawAccountNo(detailArr[1]);
			record.setUserName(detailArr[2]);
			record.setAmount(new BigDecimal(detailArr[3]));
			record.setFlag(detailArr[4]);
			record.setRemark(detailArr[5]);
			record.setAliOrderNo(detailArr[6]);
			Calendar finishTime=Calendar.getInstance();
			try {
				finishTime.setTime(sdf.parse(detailArr[7]));
			} catch (ParseException e) {
			}
			record.setFinishTime(finishTime);
			records.add(record);
		}
		return records;
	}
    
    
    @RequestMapping(value="/alipay/batch",produces = "text/html;charset=UTF-8")
	public ModelAndView requestAliBatchPay(String batchOrderNo,HttpServletRequest request,HttpServletResponse response,Model model) throws Exception{
		
		ModelAndView modelAndView = new ModelAndView("alipay_batch");
		BatchWithdrawOrder record=userService.queryBatchWithdrawOrderByOrderNo(batchOrderNo);
		List<WithdrawOrder> orders=userService.queryAliWithdrawOrderByBatchOrderNo(batchOrderNo);
		StringBuffer detail_data=new StringBuffer();
		for(int i=0;i<orders.size();i++){
			WithdrawOrder order=orders.get(i);
			detail_data.append(order.getWithdraw_order_no());
			detail_data.append("^");
			detail_data.append(order.getWithdraw_account_no());
			detail_data.append("^");
			detail_data.append(order.getReal_name());
			detail_data.append("^");
			detail_data.append(order.getWithdraw_amount().doubleValue());
			detail_data.append("^");
			detail_data.append(order.getWithdraw_desc()==null?"经纪人（"+order.getReal_name()+"）提现-"+order.getWithdraw_order_no()+"":order.getWithdraw_desc()+"【呼送科技经纪人报酬结算】");
			if(i<orders.size()-1){
				detail_data.append("|");
			}
		}
		System.out.println(detail_data.toString());
		model.addAttribute("batch_no", batchOrderNo);
		model.addAttribute("batch_fee", record.getBatch_fee().doubleValue()+"");
		model.addAttribute("batch_num", record.getBatch_num()+"");
		model.addAttribute("detail_data", detail_data.toString());
		return modelAndView;
		
	}
	
}
